package com.atom.module.mvvm.extren

import android.widget.SeekBar
import androidx.annotation.CheckResult
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate

@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
 fun SeekBar.changeEvents() = callbackFlow<SeekBarChangeEvent>  {
    checkMainThread()
    val listener = object : SeekBar.OnSeekBarChangeListener {
        override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
            trySend(
                SeekBarChangeEvent.ProgressChanged(
                    view = seekBar,
                    progress = progress,
                    fromUser = fromUser
                )
            )
        }

        override fun onStartTrackingTouch(seekBar: SeekBar) {
            trySend(
                SeekBarChangeEvent.StartTracking(view = seekBar)
            )
        }

        override fun onStopTrackingTouch(seekBar: SeekBar) {
            trySend(
                SeekBarChangeEvent.StopTracking(view = seekBar)
            )
        }
    }

    setOnSeekBarChangeListener(listener)
    awaitClose { setOnSeekBarChangeListener(null) }
}
    .conflate()
    .asInitialValueFlow {
        SeekBarChangeEvent.ProgressChanged(
            view = this,
            progress = progress,
            fromUser = false
        )
    }

 sealed class SeekBarChangeEvent {
     abstract val view: SeekBar

     data class ProgressChanged(
        override val view: SeekBar,
         val progress: Int,
         val fromUser: Boolean
    ) : SeekBarChangeEvent()

     data class StartTracking(override val view: SeekBar) : SeekBarChangeEvent()

     data class StopTracking(override val view: SeekBar) : SeekBarChangeEvent()
}

/**
 *
 */
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
 fun SeekBar.progressChanges()= callbackFlow <Int>{
    checkMainThread()
    val listener = object : SeekBar.OnSeekBarChangeListener {
        override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
            trySend(progress)
        }

        override fun onStartTrackingTouch(seekBar: SeekBar) = Unit

        override fun onStopTrackingTouch(seekBar: SeekBar) = Unit
    }

    setOnSeekBarChangeListener(listener)
    awaitClose { setOnSeekBarChangeListener(null) }
}
    .conflate()
    .asInitialValueFlow { progress }
